﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using MaxStudio.Concrete.Web;
using MaxStudio.Concrete.DBUtility;
using MaxStudio.Concrete.Server;
using MaxStudio.Concrete.Server.Service;
using MaxStudio.Concrete.Server.Dao;
using MaxStudio.Concrete.Component;
using System.Data;

namespace MaxStudio.Concrete.Web.Pages
{
    public partial class SalesOrder : BasePage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindProductInAdding();
                BindCustomer();
                BindTracker();
                BindGridView();
                WebPartBind.BindMasterDataDDL(this.ddlStatus, Int32.Parse(System.Configuration.ConfigurationSettings.AppSettings["MDSalesOrderStatus"].ToString()));
            }
        }

        #region Private Method

        private void BindProductListInEditing(int orderId)
        {
            SalesOrderService salesOrderServiceObj = ServiceFactory.getSalesOrderServices();
            OperationResult<List<tb_Mapping_OrderProduct>> MapplingResult = salesOrderServiceObj.GetMappingOrderProductByOrderId(orderId);
            if (MapplingResult.operationSuccess)
            {
                List<tb_Mapping_OrderProduct> list = MapplingResult.obj;

                DataTable dt = new DataTable();
                dt.Columns.Add("ProductId");
                dt.Columns.Add("Product");
                dt.Columns.Add("Unit");
                dt.Columns.Add("UnitId");
                dt.Columns.Add("Count");

                foreach (tb_Mapping_OrderProduct entity in list)
                {
                    string strUnitText = "";
                    if (entity.Unit == 0)
                    {
                        strUnitText = "按吨计算";
                    }
                    if (entity.Unit == 1)
                    {
                        strUnitText = "按立方计算";
                    }
                    dt.Rows.Add(entity.ProductId, entity.tb_Product.Name, strUnitText, entity.Unit, entity.Count);
                }
                EditInAddingDT = dt;
                gvEditProductAdding.DataSource = dt;
                gvEditProductAdding.DataBind();
            }
        }

        public DataTable AddInAddingDT
        {
            get
            {
                if (ViewState["AddInAddingDT"] == null)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("ProductId");
                    dt.Columns.Add("Product");
                    dt.Columns.Add("Unit");
                    dt.Columns.Add("UnitId");
                    dt.Columns.Add("Count");
                    ViewState["AddInAddingDT"] = dt;
                    return dt;
                }
                else
                {
                    return (DataTable)ViewState["AddInAddingDT"];
                }
            }
            set
            {
                ViewState["AddInAddingDT"] = value;
            }
        }

        public DataTable EditInAddingDT
        {
            get
            {
                if (ViewState["EditInAddingDT"] == null)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("ProductId");
                    dt.Columns.Add("Product");
                    dt.Columns.Add("Unit");
                    dt.Columns.Add("UnitId");
                    dt.Columns.Add("Count");
                    ViewState["EditInAddingDT"] = dt;
                    return dt;
                }
                else
                {
                    return (DataTable)ViewState["EditInAddingDT"];
                }
            }
            set
            {
                ViewState["EditInAddingDT"] = value;
            }
        }


        private void BindProductInAdding()
        {
            ProductService productServiceObj = ServiceFactory.getProductService();
            OperationResult<List<tb_Product>> result = productServiceObj.GetAllProduct();

            if (result.operationSuccess)
            {
                ddlAddProInAdding.DataSource = result.obj;
                ddlAddProInAdding.DataTextField = "Name";
                ddlAddProInAdding.DataValueField = "Id";
                ddlAddProInAdding.DataBind();
            }

        }

        private void BindProductInEditing()
        {
            ProductService productServiceObj = ServiceFactory.getProductService();
            OperationResult<List<tb_Product>> result = productServiceObj.GetAllProduct();

            if (result.operationSuccess)
            {
                ddlEditAddProInAdding.DataSource = result.obj;
                ddlEditAddProInAdding.DataTextField = "Name";
                ddlEditAddProInAdding.DataValueField = "Id";
                ddlEditAddProInAdding.DataBind();
            }

        }

        private void BindCustomer()
        {
            CustomerService customerServiceObj = ServiceFactory.getCustomerService();

            OperationResult<List<tb_Customer>> result = customerServiceObj.GetAllCustomer(1, 50);

            if (result.operationSuccess)
            {
                ddlCustomer.DataSource = result.obj;
                ddlCustomer.DataTextField = "Name";
                ddlCustomer.DataValueField = "Id";
                ddlCustomer.DataBind();
            }
        }

        private void BindTracker()
        {
            UserService userServiceObj = ServiceFactory.getUserService();

            OperationResult<List<tb_User>> result = userServiceObj.GetAllUserList();

            if (result.operationSuccess)
            {
                ddlTraker.DataSource = result.obj;
                ddlTraker.DataTextField = "Name";
                ddlTraker.DataValueField = "Id";
                ddlTraker.DataBind();
            }
            else
            {
                //EXCEPTION
                //return null;
            }
        }

        private void BindEditCustomer()
        {
            CustomerService customerServiceObj = ServiceFactory.getCustomerService();

            OperationResult<List<tb_Customer>> result = customerServiceObj.GetAllCustomer(1, 50);

            if (result.operationSuccess)
            {
                ddlEditCustomer.DataSource = result.obj;
                ddlEditCustomer.DataTextField = "Name";
                ddlEditCustomer.DataValueField = "Id";
                ddlEditCustomer.DataBind();
            }
        }

        private void BindEditTracker()
        {
            UserService userServiceObj = ServiceFactory.getUserService();

            OperationResult<List<tb_User>> result = userServiceObj.GetAllUserList();

            if (result.operationSuccess)
            {
                ddlEditTraker.DataSource = result.obj;
                ddlEditTraker.DataTextField = "Name";
                ddlEditTraker.DataValueField = "Id";
                ddlEditTraker.DataBind();
            }
            else
            {
                //EXCEPTION
                //return null;
            }
        }

        private void BindGridView()
        {
            SalesOrderService salesOrderServiceObj = ServiceFactory.getSalesOrderServices();
            OperationResult<List<tb_SalesOrder>> result = salesOrderServiceObj.GetAllSalesOrder();

            if (result.operationSuccess)
            {
                gvSalesOrderList.DataSource = result.obj;
                gvSalesOrderList.DataBind();
            }
            else
            {
                //EXCEPTION
                //return null;
            }
        }

        private void BindEdieDialog(int id)
        {
            BindEditCustomer();
            BindEditTracker();
            BindProductInEditing();
            BindProductListInEditing(id);
            WebPartBind.BindMasterDataDDL(this.ddlEditStatus, Int32.Parse(System.Configuration.ConfigurationSettings.AppSettings["MDSalesOrderStatus"].ToString()));

            SalesOrderService salesOrderServiceObj = ServiceFactory.getSalesOrderServices();
            OperationResult<tb_SalesOrder> result = salesOrderServiceObj.GetSalesOrderById(id);

            if (result.operationSuccess == true)
            {
                txtEditContranctSN.Text = result.obj.ContranctSN;
                ddlEditCustomer.SelectedValue = result.obj.CustomerId.ToString();
                txtEditSignDate.Text = result.obj.SignDate.ToShortDateString();
                txtEditFullPrice.Text = result.obj.FullPrice.ToString();
                ddlEditTraker.SelectedValue = result.obj.Traker.ToString();
                txtEditProvision.Text = result.obj.Provision;
                ddlEditStatus.SelectedValue = result.obj.Status.ToString();
                txtEditDescription.Text = result.obj.Description;

                txtEditPumpingPrice.Text = result.obj.PumpingPrice.ToString();
                txtEditOutKMPrice.Text = result.obj.OutKMPrice.ToString();
                txtEditOtherPrice.Text = result.obj.OtherPrice.ToString();
                txtEditConcretePrice.Text = result.obj.ConcretePrice.ToString();
 
                lbLastModier.Text = "TEST";
                lbEidtId.Text = result.obj.Id.ToString();
                lbLastModifyDate.Text = result.obj.ModifyDate.ToShortDateString();

            }
        }

        private void DeleteRecords(int id)
        {
            lbDeleteId.Text = id.ToString();
        }

        #region  Receivable
        private void InsertReceivable(tb_Receivable instance)
        {
            ReceivableService receivableServicObj = ServiceFactory.getReceivableService();
            OperationResult<tb_Receivable> result = receivableServicObj.CreateReceivable(instance);
        }



        #endregion

        #endregion

        #region Event
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            SalesOrderService salesOrderServiceObj = ServiceFactory.getSalesOrderServices();

            tb_SalesOrder instance = new tb_SalesOrder();

            instance.ContranctSN = txtContranctSN.Text;
            instance.CustomerId = Int32.Parse(ddlCustomer.SelectedValue.ToString());
            instance.SignDate = DateTime.Parse(txtSignDate.Text);
            instance.FullPrice = decimal.Parse(txtFullPrice.Text);
            instance.Traker = Int32.Parse(ddlTraker.SelectedValue.ToString());
            instance.Provision = txtProvision.Text;
            instance.Status = Int32.Parse(ddlStatus.SelectedValue.ToString());
            instance.Description = txtDescription.Text;

            instance.PumpingPrice = decimal.Parse(txtPumpingPrice.Text);
            instance.OutKMPrice = decimal.Parse(txtOutKMPrice.Text);
            instance.OtherPrice = decimal.Parse(txtOtherPrice.Text);
            instance.ConcretePrice = decimal.Parse(txtConcretePrice.Text);
         

            OperationResult<tb_SalesOrder> result = salesOrderServiceObj.CreateSalesOrder(instance);
            //  gvProductAdding

            for (int i = 0; i < gvProductAdding.Rows.Count; i++)
            {
                string strProductId = gvProductAdding.DataKeys[i][0].ToString();
                string strUnit = gvProductAdding.DataKeys[i][1].ToString();
                string strCount = gvProductAdding.DataKeys[i][2].ToString();
                tb_Mapping_OrderProduct mappingInstance = new tb_Mapping_OrderProduct();
                mappingInstance.ProductId = Int32.Parse(strProductId);
                mappingInstance.Unit = Int32.Parse(strUnit);
                mappingInstance.Count = Int32.Parse(strCount);
                mappingInstance.SalesOrderId = result.obj.Id;
                OperationResult<tb_Mapping_OrderProduct> mappingResult = salesOrderServiceObj.CreateOrderProductMapping(mappingInstance);
            }

            tb_Receivable receivableInstance = new tb_Receivable();
            receivableInstance.ContranctId = result.obj.Id;
            receivableInstance.HaveBill = 0; //hard code :0 -> Not , 1 -> Have
            receivableInstance.Amount = decimal.Parse(txtFullPrice.Text); ;
            receivableInstance.Traker = 1; //hard code
            receivableInstance.Round = "0";
            receivableInstance.Description = txtContranctSN.Text + " -> " + DateTime.Parse(txtSignDate.Text) + " -> " + txtFullPrice.Text;
            receivableInstance.Status = 35; // hard code
            InsertReceivable(receivableInstance);

            BindGridView();

        }
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            int editId = 0;
            if (lbEidtId.Text.Length > 0)
            {
                editId = Int32.Parse(lbEidtId.Text);
            }

            SalesOrderService salesOrderServiceObj = ServiceFactory.getSalesOrderServices();

            tb_SalesOrder entity = new tb_SalesOrder();

            entity.Id = editId;

            entity.ContranctSN = txtEditContranctSN.Text;
            entity.CustomerId = Int32.Parse(ddlEditCustomer.SelectedValue.ToString());
            entity.SignDate = DateTime.Parse(txtEditSignDate.Text);
            entity.FullPrice = decimal.Parse(txtEditFullPrice.Text);
            entity.Traker = Int32.Parse(ddlEditTraker.SelectedValue.ToString());
            entity.Provision = txtEditProvision.Text;
            entity.Status = Int32.Parse(ddlEditStatus.SelectedValue.ToString());
            entity.Description = txtEditDescription.Text;


            entity.PumpingPrice = decimal.Parse(txtEditPumpingPrice.Text);
            entity.OutKMPrice = decimal.Parse(txtEditOutKMPrice.Text);
            entity.OtherPrice = decimal.Parse(txtEditOtherPrice.Text);
            entity.ConcretePrice = decimal.Parse(txtEditConcretePrice.Text);
         

            entity.ModifyDate = DateTime.Now;
            entity.ModifyBy = 1;
            entity.CreateDate = DateTime.Now;

            OperationResult<tb_SalesOrder> resultEdit = salesOrderServiceObj.ModifySalesOrder(entity);

            BindGridView();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int deleteId = Int32.Parse(lbDeleteId.Text);
            SalesOrderService salesOrderServiceObj = ServiceFactory.getSalesOrderServices();
            tb_SalesOrder deleteEntity = new tb_SalesOrder();
            deleteEntity.Id = deleteId;
            salesOrderServiceObj.DeleteSalesOrder(deleteEntity);

            OperationResult<List<tb_Mapping_OrderProduct>> MappingResult = salesOrderServiceObj.GetMappingOrderProductByOrderId(deleteId);

            if (MappingResult.operationSuccess)
            {
                List<tb_Mapping_OrderProduct> mappingList = MappingResult.obj;

                foreach (tb_Mapping_OrderProduct entity in mappingList)
                {
                    salesOrderServiceObj.DeletetbMappingOrderProduct(entity);
                }
            }

            BindGridView();
        }

        protected void gvSalesOrderList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                string strSelectId = e.CommandArgument.ToString();
                BindEdieDialog(Int32.Parse(strSelectId));
            }

            if (e.CommandName == "del")
            {
                string strSelectId = e.CommandArgument.ToString();
                DeleteRecords(Int32.Parse(strSelectId));
            }
        }

        protected void gvSalesOrderList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvSalesOrderList.PageIndex = e.NewPageIndex;
            BindGridView();
        }

        #region Addtion



        protected void btnAddInAdding_Click(object sender, EventArgs e)
        {


            AddInAddingDT.Rows.Add(ddlAddProInAdding.SelectedValue
                                    , ddlAddProInAdding.SelectedItem.Text
                                    , ddlAddUnitInAdding.SelectedItem.Text
                                    , ddlAddUnitInAdding.SelectedValue
                                    , txtAddCountInAdding.Text);

            gvProductAdding.DataSource = AddInAddingDT;
            gvProductAdding.DataBind();

        }

        protected void gvProductAdding_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            AddInAddingDT.Rows.RemoveAt(e.RowIndex);
            gvProductAdding.DataSource = AddInAddingDT;
            gvProductAdding.DataBind();

        }
        #endregion

        #region EditProList

        protected void btnEditAddInAdding_Click(object sender, EventArgs e)
        {


            EditInAddingDT.Rows.Add(ddlEditAddProInAdding.SelectedValue
                                    , ddlEditAddProInAdding.SelectedItem.Text
                                    , ddlEditAddUnitInAdding.SelectedItem.Text
                                    , ddlEditAddUnitInAdding.SelectedValue
                                    , txtEditAddCountInAdding.Text);

            gvEditProductAdding.DataSource = EditInAddingDT;
            gvEditProductAdding.DataBind();

        }

        protected void gvEditProductAdding_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            EditInAddingDT.Rows.RemoveAt(e.RowIndex);
            gvEditProductAdding.DataSource = EditInAddingDT;
            gvEditProductAdding.DataBind();

        }



        #endregion



        #endregion







    }
}
